package com.ymx.darling.spring.mapper;

import com.ymx.darling.session.SessionFactory;
import com.ymx.darling.spring.SessionTemplate;
import org.springframework.beans.factory.FactoryBean;

/**
 * Mapper工厂Bean类，用于创建和提供Mapper接口的实例
 * 该类实现了FactoryBean接口，以便在Spring容器中使用
 *
 * @author 爱Java的小于
 * @param <T> Mapper接口的类型
 */
public class MapperFactoryBean<T> implements FactoryBean<T> {
    // SessionTemplate实例，用于执行数据库操作
    private SessionTemplate sessionTemplate;
    // Mapper接口的Class对象
    private Class<T> mapperClass;

    /**
     * 构造函数，初始化MapperFactoryBean实例
     *
     * @param mapperClass Mapper接口的Class对象
     */
    public MapperFactoryBean(Class<T> mapperClass) {
        this.mapperClass = mapperClass;
    }

    /**
     * 设置SessionTemplate实例
     *
     * @param sessionFactory SessionFactory实例，用于创建SessionTemplate
     */
    public void setSessionTemplate(SessionFactory sessionFactory) {
        this.sessionTemplate = new SessionTemplate(sessionFactory);
    }

    /**
     * 设置Mapper接口的Class对象
     *
     * @param mapperClass Mapper接口的Class对象
     */
    public void setMapperClass(Class<T> mapperClass) {
        this.mapperClass = mapperClass;
    }

    /**
     * 获取Mapper接口的实例
     *
     * @return Mapper接口的实例
     * @see SessionTemplate#getMapper(Class)
     */
    @Override
    public T getObject() {
        return sessionTemplate.getMapper(this.mapperClass);
    }

    /**
     * 获取FactoryBean生产的对象的类型
     *
     * @return Mapper接口的Class对象
     */
    @Override
    public Class<?> getObjectType() {
        return this.mapperClass;
    }
}

